package com.example.novelweb.controller;


import com.example.novelweb.common.BaseResponse;
import com.example.novelweb.common.ErrorCode;
import com.example.novelweb.common.ResultUtils;
import com.example.novelweb.exception.BusinessException;
import com.example.novelweb.exception.ThrowUtils;
import com.example.novelweb.model.dto.user.UserLoginRequest;
import com.example.novelweb.model.dto.user.UserUpdateRequest;
import com.example.novelweb.model.vo.UserVO;
import com.example.novelweb.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
  @Resource
  private UserService userService;

  // 模拟真实的短信发送，将直接返回验证码
  @PostMapping("/code")
  public BaseResponse<String> sendCodeMock(@RequestParam("account") String account) {
    return userService.sendCodeMock(account);
  }

  // 返回token
  @PostMapping("/login")
  public BaseResponse<String> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest) {
    return userService.login(userLoginRequest);
  }


  @ApiImplicitParam(name = "Authorization", value = "Authorization",required = true, dataType = "String",paramType="header")
  @PostMapping("/logout")
  public BaseResponse<Boolean> userLogout(HttpServletRequest httpServletRequest) {
    return userService.logout(httpServletRequest);
  }

  @ApiImplicitParam(name = "Authorization", value = "Authorization",required = true, dataType = "String",paramType="header")
  @GetMapping("/info")
  public BaseResponse<UserVO> getUserInfo(HttpServletRequest httpServletRequest) {
    return userService.getInfo();
  }


  @GetMapping("/info_v1")
  public BaseResponse<UserVO> getUserInfoById(Long id,HttpServletRequest httpServletRequest) {
    ThrowUtils.throwIf(id == null || id<=0, ErrorCode.PARAMS_ERROR,"null or invalid param id");
    return userService.getInfoById(id);
  }

  @ApiImplicitParam(name = "Authorization", value = "Authorization",required = true, dataType = "String",paramType="header")
  @PostMapping("/update")
  public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest httpServletRequest) {
    ThrowUtils.throwIf(userUpdateRequest==null,ErrorCode.PARAMS_ERROR);
    if(StringUtils.isAllBlank(
        userUpdateRequest.getNickname()
        ,userUpdateRequest.getAvatar()
    )) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR,"null params");
    }

    return userService.updateMe(userUpdateRequest,httpServletRequest);
  }
}
